package com.li.jiang.config;


import com.li.jiang.Exception.TokenException;
import com.li.jiang.utils.localThread.UserThreadLocal;
import com.li.jiang.utils.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * token拦截器
 **/
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //请求中获取token
        String token = request.getHeader("token");
        System.out.println("拦截器获取请求中的token:"+token);
        if(token==null){
            throw new TokenException("未添加token");
        }else {
            //        只要有token 就放行 验证交给AOP
            boolean flag = redisUtil.hasKey(token);
            if (flag){
                UserThreadLocal.setToken(token); //本地线程设置token
//            更新token时间
                redisUtil.expire(token,redisUtil.EXPR);
            }else {
                throw new TokenException("超时或者是不合法的token");
            }
        }


        return  true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();   //本地线程清空token
    }
}
